merge-requests.tsx 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414
  1. // @ts-nocheck
  2. import { PermissionAction } from '@supabase/shared-types/out/constants'
  3. import { useParams } from 'common'
  4. import { partition } from 'lodash'
  5. import { ArrowRight, GitMerge, MessageCircle, MoreVertical, Shield, X } from 'lucide-react'
  6. import { useRouter } from 'next/router'
  7. import { PropsWithChildren } from 'react'
  8. import { toast } from 'sonner'
  9. import {
  10. Button,
  11. DropdownMenu,
  12. DropdownMenuContent,
  13. DropdownMenuItem,
  14. DropdownMenuTrigger,
  15. Tooltip,
  16. } from 'ui'
  17. import { GenericSkeletonLoader } from 'ui-patterns/ShimmeringLoader'
  18. import {
  19. BranchManagementSection,
  20. BranchRow,
  21. } from '@/components/interfaces/BranchManagement/BranchPanels'
  22. import { BranchSelector } from '@/components/interfaces/BranchManagement/BranchSelector'
  23. import { PullRequestsEmptyState } from '@/components/interfaces/BranchManagement/EmptyStates'
  24. import BranchLayout from '@/components/layouts/BranchLayout/BranchLayout'
  25. import DefaultLayout from '@/components/layouts/DefaultLayout'
  26. import { PageLayout } from '@/components/layouts/PageLayout/PageLayout'
  27. import { ScaffoldContainer, ScaffoldSection } from '@/components/layouts/Scaffold'
  28. import AlertError from '@/components/ui/AlertError'
  29. import { DocsButton } from '@/components/ui/DocsButton'
  30. import NoPermission from '@/components/ui/NoPermission'
  31. import { useBranchUpdateMutation } from '@/data/branches/branch-update-mutation'
  32. import { Branch, useBranchesQuery } from '@/data/branches/branches-query'
  33. import { useGitHubConnectionsQuery } from '@/data/integrations/github-connections-query'
  34. import { useSendEventMutation } from '@/data/telemetry/send-event-mutation'
  35. import { useAsyncCheckPermissions } from '@/hooks/misc/useCheckPermissions'
  36. import { useSelectedOrganizationQuery } from '@/hooks/misc/useSelectedOrganization'
  37. import { useSelectedProjectQuery } from '@/hooks/misc/useSelectedProject'
  38. import { DOCS_URL } from '@/lib/constants'
  39. import type { NextPageWithLayout } from '@/types'
  40. const MergeRequestsPage: NextPageWithLayout = () => {
  41. const router = useRouter()
  42. const { ref } = useParams()
  43. const { data: project } = useSelectedProjectQuery()
  44. const { data: selectedOrg } = useSelectedOrganizationQuery()
  45. const isBranch = project?.parent_project_ref !== undefined
  46. const projectRef =
  47. project !== undefined ? (isBranch ? project.parent_project_ref : ref) : undefined
  48. const { can: canReadBranches, isSuccess: isPermissionsLoaded } = useAsyncCheckPermissions(
  49. PermissionAction.READ,
  50. 'preview_branches'
  51. )
  52. const {
  53. data: connections,
  54. error: connectionsError,
  55. isError: isErrorConnections,
  56. } = useGitHubConnectionsQuery({
  57. organizationId: selectedOrg?.id,
  58. })
  59. const {
  60. data: branches = [],
  61. error: branchesError,
  62. isPending: isLoadingBranches,
  63. isError: isErrorBranches,
  64. } = useBranchesQuery({ projectRef })
  65. const [[mainBranch], previewBranchesUnsorted] = partition(branches, (branch) => branch.is_default)
  66. const previewBranches = previewBranchesUnsorted.sort((a, b) =>
  67. new Date(a.updated_at) < new Date(b.updated_at) ? 1 : -1
  68. )
  69. const mergeRequestBranches = previewBranches.filter(
  70. (branch) =>
  71. branch.pr_number !== undefined ||
  72. (branch.review_requested_at !== undefined && branch.review_requested_at !== null)
  73. )
  74. const currentBranch = branches?.find((branch) => branch.project_ref === ref)
  75. const isCurrentBranchReadyForReview = !!currentBranch?.review_requested_at
  76. const githubConnection = connections?.find((connection) => connection.project.ref === projectRef)
  77. const repo = githubConnection?.repository.name ?? ''
  78. const isError = isErrorConnections || isErrorBranches
  79. const isGithubConnected = githubConnection !== undefined
  80. const { mutate: sendEvent } = useSendEventMutation()
  81. const { mutate: updateBranch, isPending: isUpdating } = useBranchUpdateMutation({
  82. onError: () => {
  83. toast.error(`Failed to update the branch`)
  84. },
  85. })
  86. const handleMarkBranchForReview = ({
  87. project_ref: branchRef,
  88. parent_project_ref: projectRef,
  89. persistent,
  90. }: Branch) => {
  91. updateBranch(
  92. {
  93. branchRef,
  94. projectRef,
  95. requestReview: true,
  96. },
  97. {
  98. onSuccess: () => {
  99. toast.success('Merge request created')
  100. // Track merge request creation
  101. sendEvent({
  102. action: 'branch_create_merge_request_button_clicked',
  103. properties: {
  104. branchType: persistent ? 'persistent' : 'preview',
  105. origin: 'merge_page',
  106. },
  107. groups: {
  108. project: projectRef ?? 'Unknown',
  109. organization: selectedOrg?.slug ?? 'Unknown',
  110. },
  111. })
  112. router.push(`/project/${branchRef}/merge`)
  113. },
  114. }
  115. )
  116. }
  117. const handleCloseMergeRequest = ({
  118. project_ref: branchRef,
  119. parent_project_ref: projectRef,
  120. }: Branch) => {
  121. updateBranch(
  122. {
  123. branchRef,
  124. projectRef,
  125. requestReview: false,
  126. },
  127. {
  128. onSuccess: () => {
  129. toast.success('Merge request closed')
  130. // Track merge request closed
  131. sendEvent({
  132. action: 'branch_close_merge_request_button_clicked',
  133. groups: {
  134. project: projectRef ?? 'Unknown',
  135. organization: selectedOrg?.slug ?? 'Unknown',
  136. },
  137. })
  138. },
  139. }
  140. )
  141. }
  142. const generateCreatePullRequestURL = (branch?: string) => {
  143. if (githubConnection === undefined) return 'https://github.com'
  144. return branch !== undefined
  145. ? `https://github.com/${githubConnection.repository.name}/compare/${mainBranch?.git_branch}...${branch}`
  146. : `https://github.com/${githubConnection.repository.name}/compare`
  147. }
  148. return (
  149. <ScaffoldContainer>
  150. <ScaffoldSection>
  151. <div className="col-span-12">
  152. <div className="space-y-4">
  153. {isPermissionsLoaded && !canReadBranches ? (
  154. <NoPermission resourceText="view this project's branches" />
  155. ) : (
  156. <>
  157. {isErrorConnections && (
  158. <AlertError
  159. error={connectionsError}
  160. subject="Failed to retrieve GitHub integration connection"
  161. />
  162. )}
  163. {isErrorBranches && (
  164. <AlertError error={branchesError} subject="Failed to retrieve preview branches" />
  165. )}
  166. {!isError && (
  167. <div className="space-y-4">
  168. {isBranch && !isCurrentBranchReadyForReview && currentBranch && (
  169. <div className="rounded-sm border rounded-lg bg-background px-6 py-4">
  170. <div className="flex items-center justify-between">
  171. <div className="flex items-center gap-2 text-sm text-foreground-light">
  172. <GitMerge strokeWidth={1.5} size={16} className="text-brand" />
  173. <span className="text-foreground">{currentBranch.name}</span>
  174. last viewed
  175. </div>
  176. <Button
  177. type="primary"
  178. size="tiny"
  179. loading={currentBranch && isUpdating}
  180. onClick={() =>
  181. currentBranch && handleMarkBranchForReview(currentBranch)
  182. }
  183. >
  184. Create merge request
  185. </Button>
  186. </div>
  187. </div>
  188. )}
  189. <BranchManagementSection
  190. header={`${mergeRequestBranches.length} merge requests`}
  191. >
  192. {isLoadingBranches ? (
  193. <div className="p-4">
  194. <GenericSkeletonLoader />
  195. </div>
  196. ) : mergeRequestBranches.length > 0 ? (
  197. mergeRequestBranches.map((branch) => {
  198. const isPR = branch.pr_number !== undefined
  199. const rowLink = isPR
  200. ? `https://github.com/${repo}/pull/${branch.pr_number}`
  201. : `/project/${branch.project_ref}/merge`
  202. return (
  203. <BranchRow
  204. isGithubConnected={isGithubConnected}
  205. key={branch.id}
  206. label={
  207. <div className="flex items-center gap-x-4">
  208. {branch.name}
  209. <ArrowRight
  210. size={14}
  211. strokeWidth={1.5}
  212. className="text-foreground-lighter"
  213. />
  214. <div className="flex items-center gap-x-2">
  215. {branch.pr_number ? (
  216. <p className="text-foreground-lighter">#{branch.pr_number}</p>
  217. ) : (
  218. <>
  219. <Shield
  220. size={14}
  221. strokeWidth={1.5}
  222. className="text-warning"
  223. />
  224. <p className="text-foreground-lighter">{mainBranch.name}</p>
  225. </>
  226. )}
  227. </div>
  228. </div>
  229. }
  230. repo={repo}
  231. branch={branch}
  232. rowLink={rowLink}
  233. external={isPR}
  234. rowActions={
  235. // We always want to show the action button to close a merge request
  236. // when user has requested review from dashboard. It doesn't matter
  237. // whether the branch is linked to a GitHub PR.
  238. branch.review_requested_at && (
  239. <DropdownMenu>
  240. <DropdownMenuTrigger asChild>
  241. <Button
  242. type="text"
  243. icon={<MoreVertical />}
  244. className="px-1"
  245. onClick={(e) => e.stopPropagation()}
  246. />
  247. </DropdownMenuTrigger>
  248. <DropdownMenuContent className="w-56" side="bottom" align="end">
  249. <Tooltip>
  250. <DropdownMenuItem
  251. className="gap-x-2"
  252. disabled={isUpdating}
  253. onSelect={(e) => {
  254. e.stopPropagation()
  255. handleCloseMergeRequest(branch)
  256. }}
  257. >
  258. <X size={14} /> Close this merge request
  259. </DropdownMenuItem>
  260. </Tooltip>
  261. </DropdownMenuContent>
  262. </DropdownMenu>
  263. )
  264. }
  265. />
  266. )
  267. })
  268. ) : (
  269. <PullRequestsEmptyState
  270. url={generateCreatePullRequestURL()}
  271. projectRef={projectRef ?? '_'}
  272. branches={previewBranches}
  273. onBranchSelected={handleMarkBranchForReview}
  274. isUpdating={isUpdating}
  275. hasGithubConnection={!!githubConnection}
  276. />
  277. )}
  278. </BranchManagementSection>
  279. </div>
  280. )}
  281. </>
  282. )}
  283. </div>
  284. </div>
  285. </ScaffoldSection>
  286. </ScaffoldContainer>
  287. )
  288. }
  289. const MergeRequestsPageWrapper = ({ children }: PropsWithChildren<{}>) => {
  290. const router = useRouter()
  291. const { ref } = useParams()
  292. const { data: project } = useSelectedProjectQuery()
  293. const { data: selectedOrg } = useSelectedOrganizationQuery()
  294. const isBranch = project?.parent_project_ref !== undefined
  295. const projectRef =
  296. project !== undefined ? (isBranch ? project.parent_project_ref : ref) : undefined
  297. const { data: branches } = useBranchesQuery({ projectRef })
  298. const previewBranches = (branches || []).filter((b) => !b.is_default)
  299. const { mutate: sendEvent } = useSendEventMutation()
  300. const { mutate: updateBranch, isPending: isUpdating } = useBranchUpdateMutation({
  301. onError: () => {
  302. toast.error(`Failed to update the branch`)
  303. },
  304. })
  305. const handleMarkBranchForReview = ({
  306. project_ref: branchRef,
  307. parent_project_ref: projectRef,
  308. persistent,
  309. }: Branch) => {
  310. updateBranch(
  311. {
  312. branchRef,
  313. projectRef,
  314. requestReview: true,
  315. },
  316. {
  317. onSuccess: () => {
  318. toast.success('Merge request created')
  319. // Track merge request creation
  320. sendEvent({
  321. action: 'branch_create_merge_request_button_clicked',
  322. properties: {
  323. branchType: persistent ? 'persistent' : 'preview',
  324. origin: 'branch_selector',
  325. },
  326. groups: {
  327. project: projectRef ?? 'Unknown',
  328. organization: selectedOrg?.slug ?? 'Unknown',
  329. },
  330. })
  331. router.push(`/project/${branchRef}/merge`)
  332. },
  333. }
  334. )
  335. }
  336. return (
  337. <PageLayout
  338. title="Merge requests"
  339. subtitle="Review and merge changes from one branch into another"
  340. primaryActions={
  341. <BranchSelector
  342. branches={previewBranches}
  343. onBranchSelected={handleMarkBranchForReview}
  344. disabled={!projectRef}
  345. isUpdating={isUpdating}
  346. />
  347. }
  348. secondaryActions={
  349. <div className="flex items-center gap-x-2">
  350. <Button
  351. asChild
  352. type="text"
  353. icon={<MessageCircle className="text-muted" strokeWidth={1} />}
  354. >
  355. <a
  356. target="_blank"
  357. rel="noreferrer"
  358. href="https://github.com/orgs/briven/discussions/18937"
  359. >
  360. Branching feedback
  361. </a>
  362. </Button>
  363. <DocsButton href={`${DOCS_URL}/guides/platform/branching`} />
  364. </div>
  365. }
  366. >
  367. {children}
  368. </PageLayout>
  369. )
  370. }
  371. MergeRequestsPage.getLayout = (page) => {
  372. return (
  373. <DefaultLayout>
  374. <BranchLayout>
  375. <MergeRequestsPageWrapper>{page}</MergeRequestsPageWrapper>
  376. </BranchLayout>
  377. </DefaultLayout>
  378. )
  379. }
  380. export default MergeRequestsPage